package cn.tanghom.framework.system.web;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.tanghom.framework.support.tree.TreeObject;
import cn.tanghom.framework.system.entity.User;
import cn.tanghom.framework.system.service.LogService;
import cn.tanghom.framework.system.service.ResourcesService;
import cn.tanghom.framework.system.service.UserService;
import cn.tanghom.framework.system.shiro.UserRealm;
import cn.tanghom.framework.utils.CommonKey;
import cn.tanghom.framework.utils.Md5Util;
import cn.tanghom.framework.utils.SingleOnlineUser;

/**
 * 帐号登录登出控制器
 * 
 * @author tanghom <tanghom@qq.com> 2015-11-18
 * 
 */
@Controller
public class LoginController {

	@Resource
	private UserService userService;
	@Resource
	private ResourcesService resourcesService;
	
	@Resource
	private LogService logService;
	
	@Resource
	private UserRealm userRealm;
	/**
	 * 登录入口
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request) {
		request.removeAttribute("error");
		return "login";
	}

	/**
	 * 登录
	 * 
	 * @param loginname
	 *            登录名
	 * @param password
	 *            密码
	 * @param request
	 *            HttpServletRequest
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(String loginname, String password, HttpServletRequest request) {
		try {
			userRealm.clearAllCache();
			Subject user = SecurityUtils.getSubject();
			password = Md5Util.encrypt(password);
			UsernamePasswordToken token = new UsernamePasswordToken(loginname, password);
			try {
				user.login(token);
			} catch (LockedAccountException lae) {
				token.clear();
				request.setAttribute("error", "用户已经被锁定不能登录，请与管理员联系！");
				return "/login";
			} catch (IncorrectCredentialsException e) {
				token.clear();
				request.setAttribute("error", "登录失败,密码错误!");
				return "/login";
			} catch (AuthenticationException e) {
				token.clear();
				request.setAttribute("error", "用户或密码不正确！");
				return "/login";
			}
			request.removeAttribute("error");
		} catch (Exception e) {
			request.setAttribute("error", "登录异常，请联系管理员！");
			return "/login";
		}
		
		Session session = SecurityUtils.getSubject().getSession();
		User user = (User) session.getAttribute(CommonKey.USER_SESSION);
		List<TreeObject> ns = resourcesService.queryResourcesTreeByUserId(user.getId());
		request.getSession().setAttribute(CommonKey.MENU_SESSION, ns);
        if (SingleOnlineUser.getMapOnline().containsKey(loginname)) {
            SingleOnlineUser.getMapOnline().remove(loginname);
        }
        SingleOnlineUser.addUser(loginname, String.valueOf(user.getId()));
		logService.add(loginname, "登录", "登录成功");
		return "redirect:main.shtml";
	}
	/**
	 * 退出，调用Shiro的退出，清空缓存
	 * 
	 * @return 登录页
	 */
	@RequestMapping("/logout")
	public String logout() {
	Session session = SecurityUtils.getSubject().getSession();
	User user = (User) session.getAttribute(CommonKey.USER_SESSION);
	if(SingleOnlineUser.getMapOnline().containsKey(user.getLoginName())){
	    SingleOnlineUser.getMapOnline().remove(user.getLoginName());
	    SecurityUtils.getSubject().logout();
	}
		return "redirect:/";
	}

}
